package com.example.criminalintent.view


import android.content.Context
import android.os.Bundle
import android.text.format.DateFormat
import android.view.*
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.criminalintent.R
import com.example.criminalintent.model.Crime
import com.example.criminalintent.model.CrimeLab


/**
 * A simple [Fragment] subclass.
 */
class CrimeListFragment : Fragment() {

    private var mRecyclerView: RecyclerView? = null
    private var mAdapter: CrimeAdapter? = null
    private var mSubtitleVisibility: Boolean = false
    private var mCallbacks: Callbacks? = null


    companion object {
        private const val SAVED_SUBTITLE_VISIBLE = "subtitle"

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val root = inflater.inflate(R.layout.fragment_crime_list, container, false)
        mRecyclerView = root.findViewById<RecyclerView>(R.id.crime_recycler_view)
        mRecyclerView!!.layoutManager = LinearLayoutManager(activity)
        if (savedInstanceState != null) {
            mSubtitleVisibility = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE)
        }
        updateUI()
        return root
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.new_crime -> {
                activity?.let {
                    val crime = Crime()
                    CrimeLab[it].addCrime(crime)
                    updateUI()
                    mCallbacks!!.onCrimeSelected(crime)
                }
                return true
            }
            R.id.show_subtitle -> {
                mSubtitleVisibility = !mSubtitleVisibility
                activity?.invalidateOptionsMenu()
                updateSubtitle()
                return true
            }
            else -> return super.onOptionsItemSelected(item)
        }
    }

    fun updateUI() {
        val crimeLab = activity?.let { CrimeLab[it] }
        val mCrimes = crimeLab!!.getCrimes()
        if (mAdapter == null) {
            mAdapter = CrimeAdapter(mCrimes)
            mRecyclerView!!.adapter = mAdapter
        } else {
            mAdapter!!.setCrimes(mCrimes)
            mAdapter!!.notifyDataSetChanged()
        }
        updateSubtitle()
    }

    private fun updateSubtitle() {
        activity?.let {
            val crimeLab = CrimeLab[it]
            val size = crimeLab.getCrimes().size
            var subtitle: String? =
                resources.getQuantityString(R.plurals.subtitle_plural, size, size)
            if (!mSubtitleVisibility) {
                subtitle = null
            }
            val activity = it as AppCompatActivity
            activity.supportActionBar?.setSubtitle(subtitle)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.fragment_crime_list, menu)
        val menuItem = menu.findItem(R.id.show_subtitle)
        if (mSubtitleVisibility) {
            menuItem.setTitle(R.string.hide_subtitle)
        } else {
            menuItem.setTitle(R.string.show_subtitle)
        }
    }


    private inner class CrimeHolder(inflater: LayoutInflater, parent: ViewGroup) :
        RecyclerView.ViewHolder(
            inflater.inflate(R.layout.list_item_crime, parent, false)
        ), View.OnClickListener {


        override fun onClick(v: View?) {
            mCallbacks!!.onCrimeSelected(mCrime!!)
        }

        var mTitleTextView: TextView? = null
        var mDateTextView: TextView? = null
        var mSolvedImageView: ImageView? = null
        var mCrime: Crime? = null

        init {
            mTitleTextView = itemView.findViewById(R.id.crime_title)
            mDateTextView = itemView.findViewById(R.id.crime_date)
            mSolvedImageView = itemView.findViewById(R.id.crime_solved)
            itemView.setOnClickListener(this)
        }

        fun bind(cur: Crime) {
            mCrime = cur
            mDateTextView?.text = DateFormat.format(getString(R.string.date_format), cur.mDate)
            mTitleTextView?.text = cur.mTitle
            mSolvedImageView?.visibility = if (mCrime!!.mSolved) {
                VISIBLE
            } else GONE
        }
    }


    private inner class CrimeAdapter(private var mCrimes: List<Crime>) :
        RecyclerView.Adapter<CrimeHolder>() {
        override fun getItemCount(): Int {
            return mCrimes.size
        }

        override fun onBindViewHolder(holder: CrimeHolder, position: Int) {
            val cur = mCrimes[position]
            holder.bind(cur)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CrimeHolder {
            val layoutInflater = LayoutInflater.from(activity)
            return CrimeHolder(layoutInflater, parent)
        }

        fun setCrimes(crimes: List<Crime>) {
            mCrimes = crimes
        }
    }

    override fun onResume() {
        super.onResume()
        updateUI()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putBoolean(SAVED_SUBTITLE_VISIBLE, mSubtitleVisibility)
    }

    interface Callbacks {
        fun onCrimeSelected(crime: Crime)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mCallbacks = context as Callbacks
    }

    override fun onDetach() {
        super.onDetach()
        mCallbacks = null
    }
}
